package day13;

public class StringTest {

	public static void main(String[] args) {
		String str = "   wang biao    ";
		System.out.println(str_trim(str));
		
		String str1 = "abcdefghijklmn";
		System.out.println(reverseString(str1));
		System.out.println(reverseString(str1, 2, 5));
		
		String str2 = "abkkbckkerkkddkkiikkee";
		System.out.println("count="+getSubStringCount(str2, "kk"));
		System.out.println("count="+getSubStringCount2(str2, "kk"));
		
		System.out.println(getMaxString("helljavaphprrr", "php"));
		
	}
	
	/******************练习1**************************/
	//模拟一个trim方法，去掉前后空格
	public static String str_trim(String str) {
		int start = 0, end = str.length()-1;
		while (start <= end && str.charAt(start) == ' ') {
			start ++;
		}
		while (start <= end && str.charAt(end) == ' ') {
			end --;
		}
		return str.substring(start,end+1);
	}
	/******************练习2**************************/
	//将一个字符串的指定部分进行反转
	public static String reverseString(String str,int beginIndex, int endIndex) {
		//字符串转换成字符数组
		char[] chs = str.toCharArray();
		//反转字符数组
		reverse(chs,beginIndex,endIndex);
		//字符数组转换成字符串
		return String.valueOf(chs);
	}
	
	private static void reverse(char[] chs, int beginIndex, int endIndex) {
		for (int start = beginIndex,end = endIndex -1; start <= end; start++,end--) {
			swop(chs, start, end);
		}
	}

	//将一个字符串进行反转
	public static String reverseString(String str) {
		return reverseString(str, 0, str.length());
	}

	/*
	
	//反转字符数组
	private static void reverse(char[] chs) {
		reverse(chs, 0, chs.length);
	}
	*/

	//置换两字字符的位置
	private static void swop(char[] chs, int start, int end) {
		char temp = chs[start];
		chs[start] = chs[end];
		chs[end] = temp;
	}
	/******************练习3**************************/
	//获取一个字符串在另一个字符串中出现的次数
	//方法一:内存中会生成很多的字符串，效率不高
	public static int getSubStringCount(String str, String key) {
		int count = 0, index = 0;
		while ((index = str.indexOf(key)) != -1) {
			str = str.substring(index+key.length());
			System.out.println(str);
			count ++;
		}
		return count;
	}
	//方法二:不建议使用split方法
	public static int getSubStringCount2(String str, String key) {
		int count = 0, index = 0;
		while ((index = str.indexOf(key,index)) != -1) {
			index = index + key.length();
			count ++;
		}
		return count;
	}
	/******************练习4**************************/
	//获取两个字符串中最大的相同子串
	public static String getMaxString(String s1, String s2) {
		String max = "", min = "";
		max = (s1.length() > s2.length()) ? s1 : s2;
		min = (max == s1) ? s2 : s1;
		for (int i = 0,len = min.length(); i < len; i++) {
			for (int j = 0,k = len - i; k != len + 1; j++,k++) {
				String temp = min.substring(j, k);
				if (max.contains(temp)) {
					return temp;
				}
			}
		}
		return "";
	}
	
}
